package com.fyzs.mp3recorder

import android.media.AudioFormat
import android.media.AudioTrack
import android.os.Bundle
import android.os.Handler
import android.os.HandlerThread
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import androidx.fragment.app.Fragment
import java.io.DataInputStream
import java.io.File

class PcmPlayerFragment : Fragment() {

    val playThread = HandlerThread("play").apply { start() }
    val playHandler = Handler(playThread.looper)

    val TAG="PcmPlayerFragment"
    companion object {
        fun newInstance(path: String?): PcmPlayerFragment {
            val f = PcmPlayerFragment()
            f.arguments = Bundle().apply { putString("filePath", path) }
            return f
        }
    }
    val audioTrack:AudioTrack by lazy {
        val sampleRate = AudioRecorderFragment.SAMPLE_RATE
        val minBufferSize = AudioTrack.getMinBufferSize(
            sampleRate,
            AudioFormat.CHANNEL_OUT_STEREO,
            AudioFormat.ENCODING_PCM_16BIT
        )
        val format = AudioFormat.Builder()
            .setEncoding(AudioFormat.ENCODING_PCM_16BIT)
            .setSampleRate(sampleRate)
            .build()
        val audioTrack = AudioTrack.Builder()
            .setAudioFormat(format)
            .setBufferSizeInBytes(minBufferSize)
            .setTransferMode(AudioTrack.MODE_STREAM)
            .build()
        audioTrack
    }


    lateinit var playButton:Button
    lateinit var stopButton:Button
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_pcm_player, container, false)
    }


    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        playButton = view.findViewById(R.id.play_btn)
        stopButton = view.findViewById(R.id.stop_btn)



        playButton.setOnClickListener {
            start()
        }
        stopButton.setOnClickListener {
            audioTrack.stop()
        }
    }

    fun start(){
        playHandler.post {
            arguments?.getString("filePath")?.run {

                Log.i(TAG, "getPcmFile: $this")

                val pcmFile = File(this)

                val dataInputStream = DataInputStream(pcmFile.inputStream())

                val buffer = ShortArray(audioTrack.bufferSizeInFrames)
                audioTrack.play()
                var l = 0
                while (dataInputStream.available().apply { l = this } > 0) {
                    //写进buffer
                    for (i in 0 until kotlin.math.min(l, buffer.size)) {
                        try {
                            buffer[i] = dataInputStream.readShort()
                        } catch (e: Exception) {
                            break
                        }
                    }
                    audioTrack.write(buffer, 0, buffer.size)
                }
                audioTrack.stop()
            }
        }
    }
}